package MarkdownManage

import (
	"FromNowOnPromote/博客系统/Tblog/controllers"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"time"
)

//上传markdown截图
type MarkdownUpload struct {
	controllers.MainController
}

type Resp struct {
	ImgFile io.Reader `json:"imgFile"`
}

func (this *MarkdownUpload) Post() {
	f, _, err1 := this.GetFile("imgFile")
	if err1 != nil {
		body := map[string]interface{}{"code": 300}
		this.Data["json"] = body
		this.ServeJSON()
		return
	}
	defer f.Close()
	t := time.Now().Unix()
	userfile := fmt.Sprintf("%d.jpg", t)
	err2 := this.SaveToFile("imgFile", "static/img/MarkdownFileSystem/"+userfile)
	if err2 != nil {
		body := map[string]interface{}{"code": 301}
		this.Data["json"] = body
		this.ServeJSON()
		return
	}
	reqUrl := fmt.Sprintf("http://127.0.0.1:5000/getMarkDown/?v=%d", t)
	body := map[string]interface{}{"code": 200, "url": reqUrl}
	this.Data["json"] = body
	this.ServeJSON()
	return
}

//获取Markdown截图接口
type MarkdownPicture struct {
	controllers.MainController
}

func (this *MarkdownPicture) Get() {
	t, err1 := this.GetInt("v")
	if err1 != nil {
		body := map[string]interface{}{"code": 301}
		this.Data["json"] = body
		this.ServeJSON()
		return
	}
	pic := fmt.Sprintf("static/img/MarkdownFileSystem/%d.jpg", t)
	p, err2 := os.Open(pic)
	defer p.Close()
	if err2 != nil {
		//用户为初始用户，为其设置一个初始图片
		pic = "static/img/avatar/logo2.png"
		p, _ = os.Open(pic)
		b, err2 := ioutil.ReadAll(p)
		if err2 != nil {
			fmt.Println(3)
			return
		}
		this.Ctx.Output.Body(b)
		return
	}
	b, err3 := ioutil.ReadAll(p)
	if err3 != nil {
		body := map[string]interface{}{"code": 302}
		this.Data["json"] = body
		this.ServeJSON()
		return
	}
	this.Ctx.Output.Body(b)
	return
}
